package cz.cvut.liy.data;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

import android.util.Log;

import java.lang.Exception;

import cz.cvut.liy.data.Test;
import cz.cvut.liy.data.Question;

public class XMLParser {
	public static Test getTest(String xmlUri) throws Exception{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlUri);
			doc.getDocumentElement().normalize();
			

			Node nodeName = doc.getDocumentElement().getElementsByTagName("name").item(0).getChildNodes().item(0);
			
			Test test = new Test(nodeName.getNodeValue());
			
			
			NodeList nodeListItems = doc.getDocumentElement().getElementsByTagName("item");
			
			for (int i = 0; i < nodeListItems.getLength(); i++){
				Element element = (Element) nodeListItems.item(i);
				Node nodeQuestion = element.getElementsByTagName("question").item(0).getChildNodes().item(0);
				Node nodeAnswer = element.getElementsByTagName("answer").item(0).getChildNodes().item(0);
				test.addQuestion(new Question(nodeQuestion.getNodeValue(), nodeAnswer.getNodeValue()));
			}

			return test;

	}

}